import FETCH from './fetch'
import qs from 'Qs'

export default {

  transferToNumber(data) {
    if (!data) return
    Object.keys(data).forEach(key=>{
      let value = data[key]
      if (value != undefined) {
        if ((typeof value == 'string' && 'true' == value.toLowerCase()) || (typeof value == 'boolean' && value)) {
          data[key] = 1
        } else if ((typeof value == 'string' && 'false' == value.toLowerCase()) || (typeof value == 'boolean' && !value)) {
          data[key] = 0
        } else if (typeof value == 'object') {
          data[key] = this.transferToNumber(value)
        }
      }
    })
    return data
  },

  get(url,params={}) {
    return FETCH.get(url,{params:this.transferToNumber(Object.assign({}, params))});
  },

  post(url,requestForm) {
    return FETCH.post(url,qs.stringify(this.transferToNumber(Object.assign({}, requestForm))))
  },

  export(url,params) {
    return exportExcel(FETCH,url,params)
  }

}

function exportExcel(fetch,url, options = {}) {
  return new Promise((resolve, reject) => {
    fetch({
      method: 'get',
      url: url,
      data: options,
      responseType: 'blob'
    }).then(
      response => {
        resolve(response.data)
        let blob = new Blob([response.data], {
          type: 'application/vnd.ms-excel'
        })
        let fileName = response.headers['content-disposition'];
        fileName = decodeURIComponent(fileName.substring(fileName.indexOf('filename=') + 9)).replace(/\"/g,'');
        console.log(fileName)
        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, fileName)
        } else {
          var link = document.createElement('a')
          link.href = window.URL.createObjectURL(blob)
          link.download = fileName
          link.click()
          window.URL.revokeObjectURL(link.href)
        }
      },
      err => {
        reject(err)
      }
    )
  })
}
